import request from '~/api/request';
import useToastBehavior from '~/behaviors/useToast';
import useAuthBehavior from '~/behaviors/useAuth';
import { isTokenExpiredError, handleTokenExpiredError, checkAndHandleAuthError } from '~/utils/auth-error-handler';

Page({
  behaviors: [useToastBehavior, useAuthBehavior],

  data: {
    isLoad: false,
    service: [],
    personalInfo: {},
    gridList: [
      {
        name: '全部发布',
        icon: 'root-list',
        type: 'all',
        url: '/packageTask/pages/task-detail/index?status=all',
      },
      {
        name: '审核中',
        icon: 'search',
        type: 'progress',
        url: '/packageTask/pages/task-detail/index?status=progress',
      },
      {
        name: '已发布',
        icon: 'upload',
        type: 'published',
        url: '/packageTask/pages/task-detail/index?status=published',
      },
      {
        name: '草稿箱',
        icon: 'file-copy',
        type: 'draft',
        url: '/packageTask/pages/task-detail/index?status=draft',
      },
    ],

    settingList: [
      { name: '我的积分', icon: 'money-circle', type: 'points', url: '/packageUser/pages/points/index' },
      { name: '联系客服', icon: 'service', type: 'service' },
      { name: '设置', icon: 'setting', type: 'setting', url: '/packageUser/pages/setting/index' },
      { name: '修改密码', icon: 'lock-on', type: 'change-password', url: '/pages/change-password/index' },
      { name: '退出登录', icon: 'logout', type: 'logout' },
    ],
  },

  async onShow() {
    // 设置tab-bar选中状态
    if (typeof this.getTabBar === 'function' && this.getTabBar()) {
      this.getTabBar().setData({
        value: 'my'
      });
    }
    
    // 检查认证状态（这会自动输出用户ID到控制台）
    const { isLoggedIn, userInfo } = this.checkAuthStatus();
    
    // 动态添加管理员功能
    this.updateSettingListForAdmin(userInfo);
    
    if (isLoggedIn) {
      try {
        // 优先使用登录时获取的用户信息，而不是调用可能不存在的模拟API
        const personalInfo = await this.getPersonalInfoFromUserData(userInfo);
        this.setData({
          isLoad: true,
          personalInfo: personalInfo || {},
        });
      } catch (error) {
        console.error('获取个人信息失败:', error);
        this.setData({
          isLoad: true,
          personalInfo: {
            name: userInfo?.name || userInfo?.username || userInfo?.nickname || '用户',
            image: userInfo?.avatar || '',
            star: 'vip',
            city: '湖南',
            points: userInfo?.points || 0
          },
        });
      }
    } else {
      this.setData({
        isLoad: false,
        personalInfo: {},
      });
    }
  },


  async getPersonalInfoFromUserData(userInfo) {
    try {
      // 调用云函数获取最新的用户信息
      const result = await wx.cloud.callFunction({
        name: 'user-management',
        data: {
          action: 'getPersonalInfo',
          data: {},
          token: wx.getStorageSync('access_token')
        }
      });
      
      // 检查是否为token过期错误
      if (checkAndHandleAuthError(result, {
        customMessage: '用户信息已过期，请重新登录'
      })) {
        return null;
      }
      
      if (result.result.success && result.result.data) {
        const userData = result.result.data;
        return {
          name: userData.name || userData.nickname || userData.username || '用户',
          image: userData.image || userData.avatar || '',
          star: userData.level || '0',
          city: userData.city || '未知',
          phone: userData.phone || '',
          email: userData.email || '',
          role: userData.role || 'user',
          level: userData.level || '普通用户',
          points: userData.points || 0
        };
      }
    } catch (error) {
      console.error('从云函数获取用户信息失败:', error);
      
      // 检查异常信息是否包含token过期错误
      if (isTokenExpiredError(error.message)) {
        handleTokenExpiredError({
          customMessage: '用户信息已过期，请重新登录'
        });
        return null;
      }
    }
    
    // 如果云函数调用失败，使用本地存储的用户信息
    if (userInfo) {
      return {
        name: userInfo.nickname || userInfo.username || userInfo.name || '用户',
        image: userInfo.avatar || '',
        star: '0',
        city: '未知',
        phone: userInfo.phone || '',
        email: userInfo.email || '',
        role: userInfo.role || 'user',
        level: userInfo.level || '普通用户',
        points: userInfo.points || 0
      };
    }
    
    // 如果都没有，返回默认值
    return {
      name: '用户',
      image: '',
      star: '用户',
      city: '未知'
    };
  },

  async getPersonalInfo() {
    try {
      const res = await request('/api/genPersonalInfo');
      const info = res.data.data;
      
      // 确保返回的数据有默认值
      return {
        name: info?.name || '用户',
        image: info?.image || '',
        star: info?.level || '0',
        city: info?.city || '未知',
        ...info
      };
    } catch (error) {
      console.error('获取个人信息失败:', error);
      // 返回默认的个人信息
      return {
        name: '用户',
        image: '',
        star: '0',
        city: '未知'
      };
    }
  },

  onLogin(e) {
    // 使用认证行为的方法跳转到登录页
    this.navigateToLogin('/pages/my/index');
  },

  onNavigateTo() {
    // 检查是否需要登录
    if (!this.requireLogin({
      message: '请先登录后再编辑个人信息'
    })) {
      return;
    }
    
    wx.navigateTo({ url: `/packageUser/pages/my/info-edit/index` });
  },

  onEleClick(e) {
    const { name, url, type } = e.currentTarget.dataset.data;
    
    // 处理退出登录
    if (type === 'logout') {
      this.logout({
        redirectUrl: '/pages/my/index'
      });
      return;
    }
    
    if (url) {
      // 如果有URL，检查是否需要登录权限
      const needAuthPages = [
        '/packageTask/pages/task-detail/index',
        '/packageUser/pages/setting/index',
        '/packageUser/pages/points/index'
      ];
      
      const needAuth = needAuthPages.some(page => url.includes(page));
      
      if (needAuth && !this.requireLogin({
        message: `请先登录后再访问${name}`
      })) {
        return;
      }
      
      // 直接跳转
      wx.navigateTo({
        url: url,
        fail: (err) => {
          console.error('页面跳转失败:', err);
          this.onShowToast('#t-toast', `跳转${name}失败`);
        }
      });
      return;
    }
    
    // 处理特殊类型的按钮
    if (type === 'service') {
      // 联系客服功能
      wx.showModal({
        title: '联系客服',
        content: '请添加客服微信：test_wechat123',
        confirmText: '复制',
        cancelText: '取消',
      });
      return;
    }
    
    // 默认显示提示
    this.onShowToast('#t-toast', `${name}功能开发中`);
  },

  /**
   * 根据用户角色动态更新设置列表
   */
  updateSettingListForAdmin(userInfo) {
    let settingList = [
      { name: '我的积分', icon: 'wallet', type: 'points', url: '/packageUser/pages/points/index' },
      { name: '联系客服', icon: 'service', type: 'service' },
      { name: '设置', icon: 'setting', type: 'setting', url: '/packageUser/pages/setting/index' },
      { name: '修改密码', icon: 'lock-on', type: 'change-password', url: '/pages/change-password/index' }
    ];

    // 如果是管理员，添加管理功能
    if (userInfo && userInfo.role === 'admin') {
      settingList.push({
        name: '用户管理',
        icon: 'user-circle',
        type: 'user-management',
        url: '/pages/user-management/index'
      });
      settingList.push({
        name: '邀请码管理',
        icon: 'link',
        type: 'invite-management',
        url: '/pages/invite-management/index'
      });
    }

    settingList.push({ name: '退出登录', icon: 'logout', type: 'logout' });

    this.setData({ settingList });
  },
});
